//
//  HRGoodsInfoViewController.m
//  haierapp
//
//  Created by zhang on 14-8-9.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRGoodsInfoViewController.h"
#import "HRAppDelegate.h"

#import "HRGoodsInfo.h"
#import "HRGoodsImageInfo.h"

#import "HRGoodsParams.h"

#import "HROrderInfoViewController.h"

#import "ActionSheet.h"


#define HIDE_IS_GOOD_HEIGHT 40.0f
#define FIXBUTTON_IN_SCROLLVIEW_OFFSET_Y (499.0f-64.0f-20.0f)-HIDE_IS_GOOD_HEIGHT

#define STATUSBAR_HEIGHT 20.0f
#define NAVIGATIONBAR_HEIGHT 44.0f
#define TABBAR_HEIGHT 49.0f
#define HEIGHT_PADDING_BOTTOM 60

//webview的高度
#define HEIGHT_WEBVIEW kScreenHeight-STATUSBAR_HEIGHT-NAVIGATIONBAR_HEIGHT-HEIGHT_PADDING_BOTTOM;

//选择商品参数类型
typedef enum {
    CHOOSE_GOODS_PARAM_TYPE_BUY,    //直接购买的商品参数
    CHOOSE_GOODS_PARAM_TYPE_INCAR   //加入购物车的商品参数
}CHOOSE_GOODS_PARAM_TYPE;

@interface HRGoodsInfoViewController ()
{
    NSArray *_carouselImages;   //幻灯片数据
    
    HRGoodsInfo *_goodsInfo;    //商品信息数据
    
    CHOOSE_GOODS_PARAM_TYPE paramType;  //针对“立即购买”的商品参数，或“加入购物车”的商品参数
    
    UIWebView *cacheWebView;
}
@property (weak, nonatomic) IBOutlet UIScrollView *myScrollView;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *shopCarView;


//商品评价、商品信息、商品参数
@property (weak, nonatomic) IBOutlet UIWebView *webView;

//图片幻灯片
@property (weak, nonatomic) IBOutlet SwipeView *carouselView;
@property (weak, nonatomic) IBOutlet UILabel *indicatorLabel;

//购买、 加入购物车
@property (weak, nonatomic) IBOutlet UIButton *buyButton;
@property (weak, nonatomic) IBOutlet UIButton *carButton;

//商品信息
@property (weak, nonatomic) IBOutlet UILabel *goodsTitle;
@property (weak, nonatomic) IBOutlet UILabel *goodsDesc;
@property (weak, nonatomic) IBOutlet UIButton *favoriteButton;

@property (weak, nonatomic) IBOutlet UILabel *goodsPrice;
@property (weak, nonatomic) IBOutlet UILabel *goodsCount;
@property (weak, nonatomic) IBOutlet UILabel *goodsExistTips;

@end

@implementation HRGoodsInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // init Carousel Data
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _myScrollView.delegate=self;
    
    //init webview
    _webView.scrollView.scrollEnabled=NO;
    _webView.scrollView.delegate=self;
    
    _carouselView.pagingEnabled=YES;

    
    
    //显示顶层navigationBar
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    UIImage *buyButtonImage=[[UIImage imageNamed:@"orange_btn"]resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    UIImage *carButtonImage=[[UIImage imageNamed:@"red_btn2"]resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    
    [_buyButton setBackgroundImage:buyButtonImage forState:UIControlStateNormal];
    [_carButton setBackgroundImage:carButtonImage forState:UIControlStateNormal];
    
    
    //隐藏页面信息
    self.myScrollView.hidden=YES;
    self.bottomView.hidden=YES;
    self.shopCarView.hidden=YES;
    
    [self showCustomLoadingHud:kLoading inView:nil];

    //加载数据
    [HRInterfaceManager getProductById:_goodsId completion:^(BOOL isSucceed, NSString *message, id data) {
        
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            //显示页面信息
            self.myScrollView.hidden=NO;
            self.bottomView.hidden=NO;
            self.shopCarView.hidden=NO;
            
            _goodsInfo=(HRGoodsInfo *)data;
            
            [self configData:_goodsInfo];
        }else{
            [self showTextHUD:message];
        }
        
        
        //页面加载耗时
        [self analysisEnd:@"商品详情页"];
    }];
   
    
}

-(void)viewDidAppear:(BOOL)animated{
    
    //解决布局问题
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }

    
    //为webview添加bottom 的 constraint
    _webView.translatesAutoresizingMaskIntoConstraints=NO;
    NSLayoutConstraint *constraint=[_webView.constraints objectAtIndex:0];
    constraint.constant=HEIGHT_WEBVIEW;
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Methods

//“立即购买”按钮事件
- (IBAction)onTapBuyButton:(id)sender {

    paramType=CHOOSE_GOODS_PARAM_TYPE_BUY;//立即购买的商品参数
    
    HRUser *user=[HRCommonData shareCommonData].curUser;
    
    if (user!=nil) {
        //提示加入购物车成功
        [self showCustomLoadingHud:kLoading inView:nil];
        
        [HRInterfaceManager addProductToShopCar:_goodsId completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideCustomLoadingHud];
            if (isSucceed) {
                
                //通知“购物车”有新商品
                [HRCommonData shareCommonData].hasNewShopCar=YES;
                
                //直接跳转到购物车
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHOW_SHOPCAR object:nil];
                
            }else{
                [self showTextHUD:message];
            }
        }];
    }else{
        //未登陆
        
        //本地判断
        int count = [[HRCommonData shareCommonData] CountProductInShopCar];
        
        if (count==SHOP_CAR_PRODUCT_COUNT_LIMIT) {
            [self showTextHUD:@"购物车商品不能超过8种"];
            return;
        }
        
        //添加到本地缓存
        [[HRCommonData shareCommonData] addProductToShopCar:_goodsInfo andProductId:_goodsId];
        
        //通知“购物车”有新商品
        [HRCommonData shareCommonData].hasNewShopCar=YES;
        
        //直接跳转到购物车
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHOW_SHOPCAR object:nil];
    }

    
}

//“加入购物车”按钮事件
- (IBAction)onTapCarButton:(id)sender {
    
    paramType=CHOOSE_GOODS_PARAM_TYPE_INCAR;//加入购物车的商品参数
    
    HRGoodsParameterViewController *paramViewController=[[HRGoodsParameterViewController alloc] initWithNibName:@"HRGoodsParameterViewController" bundle:nil];
    paramViewController.view.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    paramViewController.delegate=self;
    paramViewController.goodsId=_goodsId;
    
    [paramViewController showGoodsParamInView:self.navigationController.view];
}

//“收藏”商品
- (IBAction)onTapFavoriteGoods:(id)sender {
    
    if ([HRCommonData shareCommonData].curUser==nil) {
        [kAppDelegate showUserLoginCompletion:nil];
        
        return;
    }
    
    if (_favoriteButton.isSelected) {
        //取消收藏
        _favoriteButton.selected=NO;
        
        [self showCustomLoadingHud:kLoading inView:nil];
        
        [HRInterfaceManager deleteFavorite:_goodsId completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                [self showSuccessHud:@"已取消收藏"];
            }
        }];
        
        
    }else{
        //添加收藏
        _favoriteButton.selected=YES;
        
        [self showCustomLoadingHud:kLoading inView:nil];
        [HRInterfaceManager addFavorite:_goodsId completion:^(BOOL isSucceed, NSString *message, id data) {
            
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                
                [self showSuccessHud:@"已收藏"];
            }
        }];
        
    }
}

//给当前页面赋数据
-(void)configData:(HRGoodsInfo *)goodsInfo{
    
    self.title=goodsInfo.productTitle;
    
    //幻灯片数据
    _carouselImages=goodsInfo.productLinkerList;
    
    int count=[_carouselImages count];
    //init icarousel Indicator
    if (count==0) {
        _indicatorLabel.text=[NSString stringWithFormat:@"%d/%d",0,count];
    }else{
        _indicatorLabel.text=[NSString stringWithFormat:@"%d/%d",1,count];
    }
    
    [_carouselView reloadData];//重新加载幻灯片
    
    self.goodsTitle.text=goodsInfo.productTitle;
    self.goodsDesc.text=goodsInfo.productHalfTitle;
    NSString *sellCount=[goodsInfo.sellNum stringValue];
    self.goodsCount.text=[NSString stringWithFormat:@"%@台",sellCount];
    
    NSString *price=[NSString stringWithFormat:@"￥%.2f",[goodsInfo.unitPrice floatValue]];
    self.goodsPrice.text=price;
    
    BOOL isGoods=[goodsInfo.isGoods boolValue];
    if (!isGoods) {
        self.goodsExistTips.text=@"有货";
    }else{
        self.goodsExistTips.text=@"没货";
    }
    
    BOOL isFavorite=[goodsInfo.isFavorite isEqualToString:@"true"];
    if (isFavorite) {
        [self.favoriteButton setSelected:YES];
    }else{
        [self.favoriteButton setSelected:NO];
    }
    
    //商品信息WAP
    NSURL *goodsInfoUrl=[NSURL URLWithString:URL_WAP_GOODS_INFO(_goodsId)];
    [_webView loadRequest:[NSURLRequest requestWithURL:goodsInfoUrl]];
    
    //解决参数页面按钮不能点击
    [self cacheProductParamWebView];

}


//查看购物车
- (IBAction)showShopCar:(id)sender {
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_SHOW_SHOPCAR object:nil];
}

//缓存商品参数URL (解决WAP页面按钮，第一次加载不能点击)
-(void)cacheProductParamWebView{
    
    NSString *urlStr=URL_WAP_GOODS_PARAMS(_goodsId);
    NSURL *url=[NSURL URLWithString:urlStr];
    
    cacheWebView = [[UIWebView alloc]init];
    
    [self showCustomLoadingHud:kLoading inView:nil];
    [cacheWebView loadRequest:[NSURLRequest requestWithURL:url] progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        
    } success:^NSString *(NSHTTPURLResponse *response, NSString *HTML) {
        [self hideCustomLoadingHud];
        return HTML;
    } failure:^(NSError *error) {
        [self hideCustomLoadingHud];
    }];
    
}


#pragma mark - UIScrollView Delegate Methods


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat offsetY=scrollView.contentOffset.y;
    
    if (scrollView==_myScrollView) {
        
        if (offsetY>=FIXBUTTON_IN_SCROLLVIEW_OFFSET_Y) {
            _webView.scrollView.scrollEnabled=YES;
        }else{
            _webView.scrollView.scrollEnabled=NO;
        }
    }else if (scrollView==_webView.scrollView){
        
        if (offsetY<0) {
            _webView.scrollView.scrollEnabled=NO;
        }
        
    }
    
}


#pragma mark - Buy Goods Or Add In Car Choose Param

-(void)buyGoodsSetParam:(NSString *)goodsParam{
    
    HRUser *user=[HRCommonData shareCommonData].curUser;
    
    HRGoodsParams *goodsParamModel=[[HRGoodsParams alloc]initWithString:goodsParam usingEncoding:NSUTF8StringEncoding error:nil];
    
    BOOL hasGoods=[goodsParamModel.inventory boolValue];
    
    if (!hasGoods) {
        //当前地区，没有货
        [self showTextHUD:@"配送地区没有货"];
        
        return;
    }
    
    
    if (user!=nil) {
        //提示加入购物车成功
        [self showCustomLoadingHud:kLoading inView:nil];
        
        [HRInterfaceManager addProductToShopCar:goodsParamModel.productId completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideCustomLoadingHud];
            if (isSucceed) {
                
                //通知“购物车”有新商品
                [HRCommonData shareCommonData].hasNewShopCar=YES;
                
                if (paramType == CHOOSE_GOODS_PARAM_TYPE_BUY) {
                    //直接跳转到购物车
                    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHOW_SHOPCAR object:nil];
                }else{
                    [self showSuccessHud:@"已添加到购物车"];
                }
                
            }else{
                [self showTextHUD:message];
            }
        }];
    }else{
        //未登陆
        
        //本地判断
        int count = [[HRCommonData shareCommonData] CountProductInShopCar];
        
        if (count==SHOP_CAR_PRODUCT_COUNT_LIMIT) {
            [self showTextHUD:@"购物车商品不能超过8种"];
            return;
        }
        
        //添加到本地缓存
        [[HRCommonData shareCommonData] addProductToShopCar:_goodsInfo andProductId:goodsParamModel.productId];
        
        //通知“购物车”有新商品
        [HRCommonData shareCommonData].hasNewShopCar=YES;
        
        
        if (paramType == CHOOSE_GOODS_PARAM_TYPE_BUY) {
            //直接跳转到购物车
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHOW_SHOPCAR object:nil];
        }else{
            [self showSuccessHud:@"已添加到购物车"];
        }
    }
    
}

#pragma mark - SwipeView Datasource Delegate Methods
- (NSInteger)numberOfItemsInSwipeView:(SwipeView *)swipeView{
    return [_carouselImages count];
}

- (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view{
    
    if (view==nil) {
        view=[[UIView alloc]initWithFrame:self.carouselView.bounds];
        
        UIImageView *imageView=[[UIImageView alloc]initWithFrame:self.carouselView.bounds];
        imageView.contentMode=UIViewContentModeScaleAspectFit;
        imageView.tag=1010;
        
        [view addSubview:imageView];
        
    }
    
    HRGoodsImageInfo *imageInfo=[_carouselImages objectAtIndex:index];
    
    UIImageView *imageView=(UIImageView *)[view viewWithTag:1010];
    NSURL *imgUrl=[NSURL URLWithString:imageInfo.link];
    
    [imageView setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:IMAGENAME_PLACE_HODLE]];
    
    return view;
    
}

#pragma mark SwipeView Delegate Methods
- (void)swipeViewCurrentItemIndexDidChange:(SwipeView *)swipeView{
    int index=swipeView.currentItemIndex + 1;
    int count=[_carouselImages count];
    
    _indicatorLabel.text=[NSString stringWithFormat:@"%d/%d",index,count];
}

@end
